package gov.pbc.nn.kjgl.maintenance.handler;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.dao.CommonJdbcDao;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.Constants;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.service.IDeptService;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.AssignmentHandler;
import com.bstek.uflo.process.node.TaskNode;

/**
 * 系统技术主管
 * 
 * @author Administrator
 * 
 */
@Component(SysCTOAssignmentHandler.BEAN_ID)
public class SysCTOAssignmentHandler implements AssignmentHandler {

	public static final String BEAN_ID = "gov.pbc.nn.kjgl.maintenance.handler.SysCTOAssignmentHandler";
	@Resource(name = CommonJdbcDao.BEAN_ID)
	private CommonJdbcDao jdbcDao;

	@Resource(name = IDeptService.BEAN_ID)
	private IDeptService ds;

	@Override
	public Collection<String> handle(TaskNode node, ProcessInstance pi, Context context) {
		String sysId = (String) context.getProcessService().getProcessVariable("sysId", pi);
		String cto = (String) context.getProcessService().getProcessVariable("cto", pi);

		List<String> users = new ArrayList<String>();
		if (StringUtils.isEmpty(cto)) {
			List<IUser> list = this.getCTO(sysId);
			for (IUser u : list) {
				users.add(u.getUsername());
			}
		} else {
			users.add(cto);
		}
		return users;
	}

	public List<IUser> getCTO(String sysId) {
		String sql = "select s.OPERATION_DEPT_ID_ from t_sys_entity s where s.ID_=?";
		String deptId = this.jdbcDao.getJdbcTemplate().queryForObject(sql, new Object[] { sysId }, String.class);
		Dept dept = (Dept) ((Dept) ds.loadDeptById(deptId)).getCDept();
		List<IUser> list = SecurityUtils.getUserByRoleForDeptWithChildren(dept.getId(), Constants.ROLE_XTJSZG);
		return list;
	}
}
